package com.wswy.wzcx.ui.persenter;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.che.libcommon.api.ApiOptionalResultObserver;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.api.ProgressDialogObserver;
import com.che.libcommon.recycler.Component;
import com.che.libcommon.recycler.OnItemClickedListener;
import com.che.libcommon.recycler.RowFactory;
import com.che.libcommon.utils.RxBus;
import com.che.libcommon.utils.ToastUtils;
import com.wswy.wzcx.R;
import com.wswy.wzcx.api.Api;
import com.wswy.wzcx.model.JZCFMode;
import com.wswy.wzcx.module.InternalMsgCode;
import com.wswy.wzcx.module.core.BasePresenter;
import com.wswy.wzcx.statistics.StatTools;
import com.wswy.wzcx.statistics.StatisticsId;
import com.wswy.wzcx.ui.activity.AddDriverLicenseActivity;
import com.wswy.wzcx.ui.activity.ModuleActivity;
import com.wswy.wzcx.ui.adapter.JZCFAdapter;
import com.wswy.wzcx.ui.component.JZCFComponent;
import com.wswy.wzcx.ui.component.JZCFComponent.OnDeleteListener;
import com.wswy.wzcx.ui.data.JZCFResult;
import com.wswy.wzcx.ui.fragment.JZCFResultFragment;
import com.wswy.wzcx.ui.other.AndroidUtilities;
import com.wswy.wzcx.ui.other.DialogFactory;
import com.wswy.wzcx.ui.other.LayoutHelper;
import com.wswy.wzcx.ui.other.ViewHelp;
import com.wswy.wzcx.ui.view.JZCFView;
import com.wswy.wzcx.widget.EventMessage;
import com.wswy.wzcx.widget.JzcfEventMessage;
import com.wswy.wzcx.widget.home.RubbishFrameLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;


/**
 * Created by wangduheng26 on 2018/3/16.
 * wangduheng26@gmail.com
 */

public class JZCFPresenter extends BasePresenter {
    private Context context;
    private FrameLayout rootLayout;
    private TextView tvStartAdd;
    private RecyclerView recyclerView;
    private List<Parcelable> list;
    private BroadcastReceiver receiver;
    private JZCFAdapter adapter2;
    private JZCFView mView;
    private String messageCode = "";

    public JZCFPresenter(Context context, JZCFView view) {
        this.context = context;
        mView = view;
    }

    public void onCreate(FrameLayout frameLayout) {
        rootLayout = frameLayout;
        rootLayout.setId(ViewHelp.generateViewId());
        ProgressBar progressBar = new ProgressBar(context);
        rootLayout.addView(progressBar, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, Gravity.CENTER));
    }

    public void setupPage(String messageCode) {
        this.messageCode = messageCode;
        Api.get().fetchJZList().subscribe(new ApiOptionalResultObserver<List<JZCFMode>>() {
            @Override
            protected void onApiResult(@Nullable List<JZCFMode> list) {
                if (list == null || list.isEmpty()) {
                    showEmptyView();
                } else {
                    showListView(list);
                }
            }

            @Override
            protected void onApiError(@Nullable BaseResult result) {
                showEmptyView();
            }
        });
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.hasExtra("data")) {
                    JZCFMode mode = intent.getParcelableExtra("data");
                    boolean isEdit = intent.getBooleanExtra("isEdit", false);
                    if (list != null && !list.isEmpty()) {
                        if (isEdit) {
                            Iterator<Parcelable> iterator = list.iterator();
                            while (iterator.hasNext()) {
                                Parcelable next = iterator.next();
                                if (next instanceof JZCFMode && TextUtils.equals(mode.get_id(), ((JZCFMode) next).get_id())) {
                                    iterator.remove();
                                    break;
                                }
                            }
                        }
                        list.add(0, mode);
                        adapter2.notifyDataSetChanged();
                    } else {
                        showListView(Arrays.asList(mode));
                    }
                    queryJZCF(mode);
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(AddDriverLicenseActivity.ACTION_QUERY_JZCF);
        LocalBroadcastManager.getInstance(context).registerReceiver(receiver, filter);
    }


    private void showEmptyView() {
        rootLayout.removeAllViews();
        Context context = rootLayout.getContext();
        RelativeLayout layout = new RelativeLayout(context);
        //layout.setBackgroundColor(Color.parseColor("#f5f5f5"));


        RubbishFrameLayout layout1 = new RubbishFrameLayout(context, RubbishFrameLayout.TYPE_JZCF);
        layout1.setBackgroundColor(Color.WHITE);
//

        RelativeLayout relativeLayout = new RelativeLayout(context);
        TextView textView = new TextView(context);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
        textView.setTextColor(Color.parseColor("#444444"));
        textView.setText("你还没有添加驾驶证");
        RelativeLayout.LayoutParams layoutParams = LayoutHelper.createRelative(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT);
        LayoutHelper.setMargin(layoutParams, 20, 18, 0, 0);
        relativeLayout.addView(textView, layoutParams);
        tvStartAdd = new TextView(context);
        tvStartAdd.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
        tvStartAdd.setTextColor(ContextCompat.getColor(context, R.color.colorPrimary));
        tvStartAdd.setText("添加驾驶证");
        Drawable drawable = ContextCompat.getDrawable(context, R.drawable.arrow_right_grey).mutate();
        DrawableCompat.setTint(drawable, ContextCompat.getColor(context, R.color.colorPrimary));
        tvStartAdd.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
        layoutParams = LayoutHelper.createRelative(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        LayoutHelper.setMargin(layoutParams, 0, 0, 20, 16);
        relativeLayout.addView(tvStartAdd, layoutParams);
        LayoutHelper.setSelectable(tvStartAdd);
        tvStartAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAdd(null);
            }
        });
        layout1.addView(relativeLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        ViewCompat.setElevation(layout1, AndroidUtilities.dp(2));
        layout1.setBackground(ContextCompat.getDrawable(context, R.drawable.shape_while));

        RelativeLayout.LayoutParams params = LayoutHelper.createRelative(LayoutHelper.MATCH_PARENT, 110);
        int margin = AndroidUtilities.dp2(15);
        params.setMargins(margin, margin, margin, margin);
        layout.addView(layout1, params);

        FrameLayout frameLayout = new FrameLayout(context);
        ImageView imageView = new ImageView(context);
        frameLayout.setPadding(0, 0, 0, AndroidUtilities.dp(20));
        imageView.setImageResource(R.drawable.pic_features);
        imageView.setScaleType(ImageView.ScaleType.CENTER);
        frameLayout.addView(imageView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

        rootLayout.addView(layout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        rootLayout.addView(frameLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, Gravity.BOTTOM));

        showMenu = false;
        if (mView.activity() != null)
            mView.activity().invalidateOptionsMenu();
    }

    public boolean showMenu;

    private void showListView(List<JZCFMode> data) {
        rootLayout.removeAllViewsInLayout();
        Context context = rootLayout.getContext();
        FrameLayout layout = new FrameLayout(context);
//        layout.setBackgroundColor(ContextCompat.getColor(context, R.color.default_background_color));
        recyclerView = new RecyclerView(context);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int pos = parent.getChildAdapterPosition(view);
                if (pos == 0) {
                    outRect.top = AndroidUtilities.dp(7f);
                    outRect.left = 0;
                    outRect.right = 0;
                } else if (pos == state.getItemCount() - 1) {
                    outRect.left = AndroidUtilities.dp(15f);
                    outRect.right = AndroidUtilities.dp(15f);
                    outRect.top = AndroidUtilities.dp(7f);
                } else {
                    outRect.top = 0;
                    outRect.left = 0;
                    outRect.right = 0;
                }


            }
        });
        layout.addView(recyclerView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        rootLayout.addView(layout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
        list = new ArrayList<>(data.size() + 1);
        list.addAll(data);
        list.add(new Rect());
        adapter2 = new JZCFAdapter();

        adapter2.addFactory(JZCFMode.class, new RowFactory<JZCFMode>() {
            @Override
            public Component<JZCFMode> create(ViewGroup parent) {
                JZCFComponent component = new JZCFComponent(parent);
                component.setListener(new OnDeleteListener() {
                    @Override
                    public void onDelete(@NotNull JZCFMode data) {
                        showDeleteDialog(data);
                    }
                });
                return component;
            }
        });

        adapter2.setOnItemClickedListener(JZCFMode.class, new OnItemClickedListener<Parcelable>() {
            @Override
            public void onItemClicked(View view, Parcelable parcelable, int position) {
                JZCFMode mode = (JZCFMode) parcelable;
                if (mode.checkBeSure()) {
                    if (messageCode.equals("addJz")) {
                        EventBus.getDefault().postSticky(new JzcfEventMessage(mode));
                        mView.activity().finish();
                    } else {
                        queryJZCF(mode);
                    }
                } else {
                    startAdd(mode);
                }
                StatTools.sendClick(view.getContext(), StatisticsId.clickJZCF);
            }
        });

        adapter2.setOnItemClickedListener(Rect.class, new OnItemClickedListener<Parcelable>() {
            @Override
            public void onItemClicked(View view, Parcelable parcelable, int position) {
                startAdd(null);
            }
        });


        adapter2.setItems(list);
//                JZCFAdapter adapter = new JZCFAdapter(list);
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter2);
        showMenu = true;

        if (mView.activity() != null) {
            mView.activity().invalidateOptionsMenu();
        }

    }


    private void showDeleteDialog(final JZCFMode data1) {
        DialogFactory.create(context, "温馨提示",
                TextUtils.concat("删除", data1.getNumber(), "的驾驶证？").toString(), "确定", "取消",
                new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Api.get().deleteJZCFMode(data1.get_id())
                                .subscribe(new ProgressDialogObserver<String>(context, "", "正在删除") {
                                    @Override
                                    protected void onApiResult(@Nullable String s) {
                                        removeFromList(data1);
                                        RxBus.getDefault().postWithCode(InternalMsgCode.CODE_DELETE_JZ, data1);
                                    }

                                    @Override
                                    protected void onApiError(@Nullable BaseResult result) {
                                        toastErrorMsg(result);
                                    }
                                });
                    }
                }).show();
    }

    private void removeFromList(JZCFMode data1) {
        int i = list.indexOf(data1);
        list.remove(data1);
        if (list.size() <= 1) {
            list.clear();
            showEmptyView();
        } else {
            adapter2.notifyItemRemoved(i);
        }

    }

    private void startAdd(JZCFMode mode) {
        Intent intent = new Intent(context, AddDriverLicenseActivity.class);
        if (mode != null) {
            intent.putExtra("data", mode);
        }
        context.startActivity(intent);
        if (mode == null) {
            StatTools.sendClick(context, StatisticsId.clickJZCFAdd);
        }
    }

    private void queryJZCF(final JZCFMode mode) {
        if (mode != null) {
            ProgressDialogObserver<JZCFResult> observer = new ProgressDialogObserver<JZCFResult>(context, "提示", "正在查询") {
                @Override
                protected void onApiResult(@Nullable JZCFResult result) {
                    if (result != null && context != null) {
                        Intent intent = ModuleActivity.getTargetIntent(context, JZCFResultFragment.TAG);
                        intent.putExtra("data", result);
                        context.startActivity(intent);
                    }

                }

                @Override
                protected void onApiError(@Nullable BaseResult result) {
                    toastErrorMsg(result);
                    if (result != null && result.statusCode == 106006) {
                        mode.setStatus(106006);
                        if (adapter2 != null) adapter2.notifyDataSetChanged();
                    }
                }
            };
            Api.get().fetchJZCFResult(mode.get_id(), mode.getFileNumber(), mode.getNumber())
                    .subscribe(observer);

        }
    }

    public void onDestroy() {
        if (receiver != null)
            LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver);
        context = null;

    }

    public void setShowEditMode() {
        adapter2.setEditMode();
        if (mView.activity() != null) {
            mView.activity().invalidateOptionsMenu();
        }

    }

    public void onResume() {
        exitEdit();
    }

    public void onStart() {
        exitEdit();
    }

    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        if (!showMenu) return;
        if (adapter2 == null || !adapter2.getMode()) {
            inflater.inflate(R.menu.menu_edit, menu);
            MenuItem item = menu.findItem(R.id.action_edit);
            SpannableString s = new SpannableString(item.getTitle());
            s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.colorPrimary)), 0, s.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            item.setTitle(s);
        } else {
            inflater.inflate(R.menu.menu_complete, menu);
            MenuItem item = menu.findItem(R.id.action_edit_complete);
            SpannableString s = new SpannableString(item.getTitle());
            s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(context, R.color.colorPrimary)), 0, s.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
            item.setTitle(s);
        }

    }

    public void exitEdit() {
        if (adapter2 != null) adapter2.exitEditMode();
        if (mView.activity() != null) {
            mView.activity().invalidateOptionsMenu();
        }
    }


}
